package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.RedisCacheService;
import com.heima.model.schedule.dtos.TaskDto;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {

    @Autowired
    private ThreadPoolTaskExecutor threadPool;

    /**
     * 添加延迟任务
     *
     * @param taskDto
     * @return
     */
    @Override
    public long addTask(TaskDto taskDto) {

        Future<Long> future = threadPool.submit(new Callable<Long>() {
            @Override
            public Long call() throws Exception {
                //1.添加任务到数据库表中，taskinfo 和taskinfologs
                boolean flag = addTaskToDb(taskDto);
                if (flag) {
                    //添加任务到redis中
                    addTaskToCache(taskDto);
                }
                System.out.println("活动线程:" + threadPool.getActiveCount());
                //TODO 考虑当前task.getTaskId()是否有值？
                return taskDto.getTaskId();
            }
        });

        try {
            return future.get();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 取消任务
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean cancelTask(long taskId) {

        boolean flag = false;

        //删除任务，更新日志
        TaskDto taskDto = updateDb(taskId, ScheduleConstants.EXECUTED);

        //删除redis的数据
        if (taskDto != null) {
            removeTaskFromCache(taskDto);
            flag = true;
        }


        return false;
    }

    @Override
    public TaskDto poll(int type, int priority) {
        /**
         * 按照类型和优先级来拉取任务
         * 消费任务，一定是从redis中list队列中拉取任务，不涉及zset队列
         * @param type
         * @param priority
         * @return
         */
        //使用多线程的方式
        Future<TaskDto> future = threadPool.submit(new Callable<TaskDto>() {
            @Override
            public TaskDto call() throws Exception {
                String keySuffix = type + "_" + priority;
                //1.从redis的list中取出数据并删除
                String taskStr = redisCacheService.lRightPop(ScheduleConstants.TOPIC + keySuffix);
                if (taskStr != null) {
                    //3.把获取到taskStr转化成对象类型，从而获取taskId参数
                    TaskDto task = JSON.parseObject(taskStr, TaskDto.class);
                    //2.修改数据库的表，删除任务表以及修改任务日志表的状态以及version
                    taskinfoMapper.deleteById(task.getTaskId());
                    TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(task.getTaskId());
                    if (taskinfoLogs != null) {
                        taskinfoLogs.setStatus(ScheduleConstants.EXECUTED);//表示消费状态
                        //按照正常来说我们还要对version更新,此时不需要，因为mp已经集成version乐观锁
                        //taskinfoLogs.setVersion();
                        taskinfoLogsMapper.updateById(taskinfoLogs);
                    }
                    //4.返回数据
                    return task;
                }
                return null;
            }
        });
        try {
            return future.get();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }



    /**
     * 删除redis中的任务数据
     *
     * @param taskDto
     */
    private void removeTaskFromCache(TaskDto taskDto) {

        String key = taskDto.getTaskType() + "_" + taskDto.getPriority();

        if (taskDto.getExecuteTime() <= System.currentTimeMillis()) {
            redisCacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(taskDto));
        } else {
            redisCacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(taskDto));
        }
    }

    /**
     * 删除任务，更新任务日志状态
     *
     * @param taskId
     * @param status
     * @return
     */
    private TaskDto updateDb(long taskId, int status) {
        TaskDto taskDto = null;
        try {
            //删除任务
            taskinfoMapper.deleteById(taskId);

            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            taskDto = new TaskDto();
            BeanUtils.copyProperties(taskinfoLogs, taskDto);
            taskDto.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (Exception e) {
            log.error("task cancel exception taskid={}", taskId);
        }

        return taskDto;

    }


    @Autowired
    private RedisCacheService redisCacheService;

    /**
     * 把任务添加到redis中
     *
     * @param taskDto
     */
    private void addTaskToCache(TaskDto taskDto) {

        String key = taskDto.getTaskType() + "_" + taskDto.getPriority();

        //2.1 如果执行时间小于当前时间，则存入list中
        if (taskDto.getExecuteTime() <= System.currentTimeMillis()) {
            redisCacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(taskDto));
        }
        //2.2如果执行时间大于当前时间，小于预设时间(当前时间+5分钟)，则存入zset中
        //获取预设时间=当前时间+5分钟
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        //获取当前时间的5分钟之后的毫秒值
        long fiveTime = calendar.getTimeInMillis();
        if (taskDto.getExecuteTime() > System.currentTimeMillis() && taskDto.getExecuteTime() <= fiveTime) {
            redisCacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(taskDto), taskDto.getExecuteTime());
        }


    }

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    /**
     * 添加任务到数据库中
     *
     * @param taskDto
     * @return
     */
    private boolean addTaskToDb(TaskDto taskDto) {

        boolean flag = false;

        try {
            //保存任务表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(taskDto, taskinfo);
            taskinfo.setExecuteTime(new Date(taskDto.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            //设置taskID
            taskDto.setTaskId(taskinfo.getTaskId());

            //保存任务日志数据
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);

            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return flag;
    }

    /**
     * 未来数据定时刷新
     */
    @Scheduled(cron = "*/1 * * * * ?")
    public void refresh() {

//暂时把锁去掉，避免影响测试
        // String token = redisCacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        //if(StringUtils.isNotBlank(token)){

        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println(System.currentTimeMillis() / 1000 + "执行了定时任务");

                try {
                    //休眠2秒钟
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //1.获取所有未来数据的keys
                Set<String> futureKeys = redisCacheService.scan("*_future");
                //根据所有的key获取value值
                for (String futureKey : futureKeys) { //futureKey= 50_100_future
                    Set<String> taskSet = redisCacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                    if(taskSet!=null && taskSet.size()>0){
                        //2.采用redis管道的方式同步到list中
                        String topicKey=futureKey.split("_future")[0]+"_topic";

                        /**
                         * 采用redis管道方式进行数据同步
                         * refreshWithPipeline(String future_key,String topic_key,Collection<String> values)
                         * 参数1 表示未来数据的key
                         * 参数2 表示list数据的key
                         * 参数3表示要进行同步的数据集合
                         *  表示从未来数据同步到list数据中
                         */
                        redisCacheService.refreshWithPipeline(futureKey,topicKey,taskSet);
                        System.out.println("成功的将" + futureKey + "下的当前需要执行的任务数据刷新到" + topicKey + "下");
                    }
                }
                //  }

            }
        });

    }

    @Scheduled(cron = "0 */5 * * * ?")
    @PostConstruct
    public void reloadData() {
        clearCache();
        log.info("数据库数据同步到缓存");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);

        //查看小于未来5分钟的所有任务
        List<Taskinfo> allTasks = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar.getTime()));
        if (allTasks != null && allTasks.size() > 0) {
            for (Taskinfo taskinfo : allTasks) {
                TaskDto taskDto = new TaskDto();
                BeanUtils.copyProperties(taskinfo, taskDto);
                taskDto.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskToCache(taskDto);
            }
        }
    }

    private void clearCache() {
        // 删除缓存中未来数据集合和当前消费者队列的所有key
        Set<String> futurekeys = redisCacheService.scan(ScheduleConstants.FUTURE + "*");// future_
        Set<String> topickeys = redisCacheService.scan(ScheduleConstants.TOPIC + "*");// topic_
        redisCacheService.delete(futurekeys);
        redisCacheService.delete(topickeys);
    }
}